package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Q0056 {
    public int[][] merge(int[][] intervals) {
        List<int[]> list = new ArrayList<>();
        Arrays.sort(intervals, (o1, o2) -> o1[0] == o2[0] ? o1[1] - o2[1] : o1[0] - o2[0]);
        int l = -1;
        int r = -1;
        for (int[] a : intervals) {
            if (a[0] > r) {
                if (r != -1) {
                    list.add(new int[]{l, r});
                }
                l = a[0];
                r = a[1];
            } else {
                r = Math.max(r, a[1]);
            }
        }
        list.add(new int[]{l, r});
        int[][] res = new int[list.size()][2];
        for (int i = 0; i < res.length; i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}
